package com.seal.tsms.base.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.seal.tsms.base.dao.QueryParser;
import com.seal.tsms.base.log.BaseLog;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.File;
import java.util.Properties;

/**
 * spring4 零xml配置
 * 此类的作用类似于  applicationContext.xml
 * Created by seal.jing on 2015/12/20.
 */
@Configuration
@ComponentScan(basePackages = "com.seal.tsms", excludeFilters = { @ComponentScan.Filter(value = { Controller.class }) })
@PropertySource({"classpath:properties/datasource.properties","classpath:properties/other.properties"})
@EnableTransactionManagement
@EnableAspectJAutoProxy
public class ApplicationConfig extends BaseLog {

    @Autowired
    private Environment env;

    /**
     * 数据源
     * @return
     */
    @Bean
    public DataSource dataSource(){

        try {
            ComboPooledDataSource bean=new ComboPooledDataSource();
            bean.setDriverClass(env.getProperty("jdbc.driverClassName"));
            bean.setJdbcUrl(env.getProperty("jdbc.url"));
            bean.setUser(env.getProperty("jdbc.username"));
            bean.setPassword(env.getProperty("jdbc.password"));
            bean.setAutoCommitOnClose(Boolean.parseBoolean(env.getProperty("cpool.autoCommitOnClose")));
            bean.setCheckoutTimeout(Integer.parseInt(env.getProperty("cpool.checkoutTimeout")));
            bean.setInitialPoolSize(Integer.parseInt(env.getProperty("cpool.minPoolSize")));
            bean.setMinPoolSize(Integer.parseInt(env.getProperty("cpool.minPoolSize")));
            bean.setMaxPoolSize(Integer.parseInt(env.getProperty("cpool.maxPoolSize")));
            bean.setMaxIdleTime(Integer.parseInt(env.getProperty("cpool.maxIdleTime")));
            bean.setAcquireIncrement(Integer.parseInt(env.getProperty("cpool.acquireIncrement")));
            bean.setMaxIdleTimeExcessConnections(Integer.parseInt(env
                    .getProperty("cpool.maxIdleTimeExcessConnections")));

            return bean;
        } catch (PropertyVetoException e) {
           throw new RuntimeException(e);
        }

    }

    /**
     * hibernate sessionFactory
     * @return
     */
    @Bean(autowire = Autowire.BY_TYPE)
    public FactoryBean<SessionFactory> sessionFactory(){
        try {
            log.info("解析外部查询");
            QueryParser.createAllQueryTemplateMap();
            log.info("完成外部查询解析");
        } catch (Exception e) {
            log.error("解析外部查询出现错误",e);
            e.printStackTrace();
        }
        LocalSessionFactoryBean bean=new LocalSessionFactoryBean();
        bean.setPackagesToScan(env.getProperty("hibernate.packagesToScan").split(","));
        bean.setConfigLocation(new ClassPathResource("hibernate.cfg.xml"));

        Properties hibernateProperties = new Properties();
        //hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
        //hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
        //hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
        hibernateProperties.setProperty("hibernate.query.substitutions", env.getProperty("hibernate.query.substitutions"));
        hibernateProperties.setProperty("hibernate.jdbc.fetch_size", env.getProperty("hibernate.jdbc.fetch_size"));
        hibernateProperties.setProperty("hibernate.jdbc.batch_size", env.getProperty("hibernate.jdbc.batch_size"));
        hibernateProperties.setProperty("hibernate.cache.region.factory_class",
                env.getProperty("hibernate.cache.region.factory_class"));
        hibernateProperties.setProperty("hibernate.cache.use_second_level_cache",
                env.getProperty("hibernate.cache.use_second_level_cache"));
        hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));
        hibernateProperties.setProperty("hibernate.transaction.coordinator_class",
                env.getProperty("hibernate.transaction.coordinator_class"));
        hibernateProperties.setProperty("hibernate.cache.provider_configuration_file_resource_path",
                env.getProperty("hibernate.cache.provider_configuration_file_resource_path"));
        hibernateProperties.setProperty("hibernate.search.default.directory_provider",
                env.getProperty("hibernate.search.default.directory_provider"));
       // String indexBase = getDataFilePath() + "/indexes";
       // (new File(indexBase)).mkdirs();
       // hibernateProperties.setProperty("hibernate.search.default.indexBase", indexBase);

        bean.setHibernateProperties(hibernateProperties);

        return bean;
    }
    /**
     * Hibernate事务管理
     *
     * @return
     */
    @Bean(autowire = Autowire.BY_TYPE)
    public HibernateTransactionManager hibernateTransactionManager() {
        HibernateTransactionManager bean = new HibernateTransactionManager();
        return bean;
    }
    /**
     * 邮件发送服务实现
     *
     * @return
     */
    @Bean
    public JavaMailSenderImpl javaMailSender() {
        JavaMailSenderImpl bean = new JavaMailSenderImpl();
        bean.setDefaultEncoding(env.getProperty("mail.smtp.defaultEncoding"));
        bean.setPort(env.getProperty("mail.smtp.port", Integer.class));
        bean.setHost(env.getProperty("mail.smtp.host"));
        bean.setUsername(env.getProperty("mail.smtp.username"));
        bean.setPassword(env.getProperty("mail.smtp.password"));

        Properties javaMailProperties = new Properties();
        javaMailProperties.setProperty("mail.smtp.auth", env.getProperty("mail.smtp.auth"));
        javaMailProperties.setProperty("mail.smtp.timeout", env.getProperty("mail.smtp.timeout"));
        bean.setJavaMailProperties(javaMailProperties);
        return bean;
    }
    /**
     * 任务计划工厂类配置
     *
     * @return
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        Properties quartzProperties = new Properties();
        quartzProperties.setProperty("org.quartz.threadPool.threadCount", "3");
        bean.setQuartzProperties(quartzProperties);
        return bean;
    }



}
